package com.leyou.item.web;

import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 根据id查询分类
     *
     * @param id 分类的id
     * @return 分类对象
     */
    @GetMapping("/{id}")
    public ResponseEntity<CategoryDTO> queryCategoryById(@PathVariable("id") Long id) {
        // 根据id查询
        Category category = categoryService.getById(id);
        // 转DTO
        CategoryDTO categoryDTO = new CategoryDTO(categoryService.getById(id));
        // 封装结果，返回200
        return ResponseEntity.ok(categoryDTO);
    }

    /**
     * 根据id集合查询分类集合
     *
     * @param ids 分类的id集合
     * @return 分类对象集合
     */
    @GetMapping("/list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids") List<Long> ids) {
        // 根据id批量查询
        List<Category> list = categoryService.listByIds(ids);
        // 转换DTO
        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(list);
        /*List<CategoryDTO> dtoList = list // List<Category>
                .stream() // Stream<Category>
                .map(CategoryDTO::new) // Stream<CategoryDTO>
                .collect(Collectors.toList()); // List<CategoryDTO>*/
        /*List<CategoryDTO> dtoList = new ArrayList<>(list.size());
        for (Category category : list) {
            dtoList.add(new CategoryDTO(category));
        }*/
        // 返回200
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据父分类的id，查询子分类的集合
     *
     * @param parentId 父分类的id
     * @return 子分类的集合
     */
    @GetMapping("/of/parent")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByParentId(@RequestParam("pid") Long parentId) {
        // SELECT * FROM tb_category WHERE parent_id = 0
        List<Category> list = categoryService.query().eq("parent_id", parentId).list();
        // 转DTO
        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(list);
        // 返回200
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据品牌id查询分类
     * @param brandId 品牌id
     * @return 分类集合
     */
    @GetMapping("/of/brand")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByBrandId(@RequestParam("id") Long brandId){
        List<CategoryDTO> dtoList = categoryService.queryCategoryByBrandId(brandId);
        return ResponseEntity.ok(dtoList);
    }
}
